
<template>
	<div>
		<div>
			<h2>Sa-Token SSO-Client 应用端</h2>
			<p>当前会话是否登录：{{isLogin}}</p>
			<p>
				<a style="margin-left: 20px" @click="login" :href="`${clientUrl}/sso/login?back=${encodeURIComponent(back)}`">登录</a>
				<a style="margin-left: 20px" @click="logout" :href="`${clientUrl}/sso/logout?back=${encodeURIComponent(back)}`">注销</a>
				<el-button style="margin-left: 20px" type="primary" @click="login">登录</el-button>
				<el-button style="margin-left: 20px" type="danger" @click="logout">注销</el-button>
			</p>
		</div>
	</div>
</template>
<script >
import axios from "axios";

export default {

	created() {
		// this.getIsLogin();
		// this.judgeLogin();
	},
	mounted() {
		this.judgeLogin();
	},
	data(){
		return {
			clientUrl: 'http://localhost:9002',
			isLogin:false,
			back:window.location.href,
			redirectUrl: 'http://localhost:8002/client'
		}
	},
	methods:{
		login(){
			window.location.href = this.clientUrl + "/sso/login?back=" + encodeURIComponent(this.back)
		},
		// 获取cookie中的值
		getCookieValueByName(name) {
			// 将document.cookie分割成一个数组
			var cookieArray = document.cookie.split(';');
			// 去除每个cookie前后的空格，并创建一个键值对对象数组
			var cookieMap = cookieArray.map(function(cookie) {
				var parts = cookie.split('=');
				return {
					key: parts[0].trim(),
					value: parts[1] ? parts[1].trim() : ''
				};
			});
			// 查找对应的cookie值
			for(var i = 0; i < cookieMap.length; i++) {
				if(cookieMap[i].key === name) {
					return cookieMap[i].value;
				}
			}
			return null; // 如果没有找到，返回null
		},
		logout(){
			// 跳转到logout
			window.location.href = this.clientUrl + "/sso/logout?back=" + encodeURIComponent(this.back)
			localStorage.removeItem('satoken')
			// 删除cookie
			// document.cookie = 'satoken=;expires=Thu, 01 Jan 1970 00:00:00 GMT;Max-Age=0; SameSite=Lax; secure; path=/;'
		},
		// 判断用户是否登录
		judgeLogin(){
			// let satoken = document.cookie.split("satoken=")[1];
			// let satoken = this.getCookieValueByName('satoken')
			// if(satoken == null){
			// 	this.$set(this,'isLogin',true)
			// 	this.$message.success("已成功登录！")
			// }else {
			// 	this.$message.error("未登录！")
			// 	this.$set(this,'isLogin',false)
			// }
			// localStorage.setItem('satoken',satoken)
			let satoken = this.getCookieValueByName('satoken')
			axios.get(this.clientUrl + "/isLogin/" + satoken).then(res =>{
				this.isLogin = res.data
				if(this.isLogin){
					if (localStorage.getItem('satoken') == null){
						localStorage.setItem('satoken',satoken)
					}
					this.$message.success("已登录！")
				}else {
					this.$message.error("未登录！")
				}
			});

		},
	}

}
</script>

<style scoped lang="scss">

</style>